﻿using System;
using System.Linq;

namespace MikadoShooter
{
    public class DrawTarget : DrawBase
    {
        private readonly Level level;
        private readonly SoundPlayer soundPlayer;
        private Vector4Target Target { get { return (Vector4Target)Vector4Base; } }

        public DrawTarget(out TargetAction targetAction, Level level, SoundPlayer soundPlayer) : base(CalcVerticals(level.Lines), level.CurrentLevel.Targets)
        {
            this.level = level;
            this.soundPlayer = soundPlayer;
            targetAction = new TargetAction(GetTargets, MissTarget, RemoveTarget);
        }

        //Closer!
        private bool MissTarget()
        {
            for (int i = 0; i < Data.Length; i += 2)
            {
                //Skip allready removed
                if (Target.IsRemoved[i / 2])
                    continue;

                //Move line down
                if (Data[i].Y >= -1.0f)
                    Data[i].Y -= 0.05f;

                //Check for endline
                if (Data[i].Y <= -0.8f)
                {
                    soundPlayer.PlaySound(eSoundname.Restart);

                    Vector4Target restartLevel = level.Restart();
                    Update(restartLevel.Data.Count() / 2, restartLevel);
                    level.MessageBox.NewMessage("Restart");
                    return false;
                }
            }

            return true;
        }

        //Remove the line
        private bool RemoveTarget(int[] lineIndex)
        {
            //Dummy check
            if (lineIndex.Length != 2)
                throw new ArgumentException("Line index error");

            //Mark as removed
            Target.IsRemoved[lineIndex[0]/2] = true;
            Target.IsRemoved[lineIndex[1]/2] = true;

            //Move out of screen
            Data[lineIndex[0]].Y = -1.1f;
            Data[lineIndex[1]].Y = -1.1f;

            //Check if all is removed
            if (Target.IsRemoved.Count(x => x) == Data.Length / 2)
            {
                soundPlayer.PlaySound(eSoundname.Complete);

                Vector4Target nextLevel = level.NextLevel();
                Update(nextLevel.Data.Count() / 2, nextLevel);
                level.MessageBox.NewMessage("Next Level" + Environment.NewLine + level.LevelNr);
                return false;
            }

            return true;
        }

        public static int CalcVerticals(int levelLines)
        {
            return levelLines * 2;
        }

        private Vector4Target GetTargets()
        {
            return Target;
        }
    }
}